#!/usr/bin/env python

import sys
from stats_class import Stats
import datetime
import calendar
from os3.types.odict import odict
from collections import defaultdict

def log ( liwe, module = '', id_ref = '', event = 'view', uid = 0 ):
	"""
	:INPUT:

		- module:			SAFE_DB_STRING
		- id_ref:			SAFE_DB_STRING
		- event:			SAFE_DB_STRING
		- uid:				SAFE_NUMBER
	"""

	s = Stats ( liwe )
	s.log ( module, id_ref, event, uid = uid )

	return { 'status': 'ok' }

def graph ( liwe, module = '', id_ref = '', event = '', log_start = '', log_end = '', log_type = 'day' ):
	"""
	:INPUT:

		- module:			SAFE_DB_STRING
		- id_ref:			SAFE_DB_STRING
		- event:			SAFE_DB_STRING
		- log_start:			SAFE_DATE
		- log_end:			SAFE_DATE
		- log_type:			SAFE_DB_STRING
	"""

	s = Stats ( liwe )

	result = s.data ( module, id_ref, event, log_start, log_end, log_type )
	
	if not result: return {}
	
	labels = []
	keys = []

	start = min ( x [ 'period' ] for x in result )
	end = max ( x [ 'period' ] for x in result )

	def get_year_month ( year_month ):
		year_month = str ( year_month )
		return [ int ( n ) for n in ( year_month [ : 4 ], year_month [ 4 : ] ) ]

	if log_type == 'day':
		curr_date = start
		while curr_date <= end:
			labels.append ( curr_date.strftime ( '%d-%m' ) )
			curr_date += datetime.timedelta ( days = 1 )
		keys = labels
	elif log_type == 'hour':
		labels = [ str ( x ) for x in range ( 24 ) ]
		keys = labels
	elif log_type == 'month':
		year_min, month_min = get_year_month ( start )
		year_max, month_max = get_year_month ( end )
		for y in range ( year_min, year_max + 1):
			if year_min == year_max:
				months = range ( month_min, month_max + 1 )
			elif y == year_min:
				months = range ( month_min, 13 )
			elif y == year_max:
				months = range ( 1, month_max + 1 )
			else:
				months = range ( 1, 13 )
			labels += [ "%s %d" % ( calendar.month_name [ m ], y ) for m in months ]
			keys += [ "%d%02d" % ( y, m ) for m in months ]
	elif log_type == 'year':
		labels = [ str ( x ) for x in range ( start, end + 1 ) ]
		keys = labels
	elif log_type == 'week':
		labels = [ str ( x ) for x in range ( 1, 54 ) ]
		keys = labels
	elif log_type == 'weekday':
		labels = [ calendar.day_name [ n ] for n in range ( 7 ) ]
		keys = [ str ( n ) for n in range ( 7 ) ]

	if event == '':
		event = 'tutti'

	table = defaultdict ( dict )
	for row in result:
		period = row [ 'period' ]

		if isinstance ( period, datetime.date ):
			period = period.strftime ( '%d-%m' )
		else:
			period = str ( period )

		if event == '__all':
			table [ row [ 'event' ] ] [ period ] = row [ 'value' ]
		else:
			table [ event ] [ period ] = row [ 'value' ]

	data = defaultdict ( list )
	for key in keys:
		#sys.stderr.write ( 'KEY = %s\n' % key )
		for event in table.keys ():
			data [ event ].append ( table [ event ].get ( key ) )

	if len ( labels ) > 10:
		new_labels = {}
		step = len ( labels ) / 10
		for x in range ( 0, len ( labels ), step ):
			new_labels [ x ] = labels [ x ]
		labels = new_labels

	return {
		'data': data,
		'labels': labels
	}

